package com.base.maintain;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NestedRegexMatcher implements StringMatcher {
	private List<Pattern> regexPatterns;

	public NestedRegexMatcher(List<Pattern> regexPatterns) {
		super();
		this.regexPatterns = regexPatterns;
	}

	public NestedRegexMatcher(String... regexs) {
		super();
		regexPatterns = new ArrayList<Pattern>();
		for (String regex : regexs) {
			regexPatterns.add(Pattern.compile(regex));
		}
	}

	@Override
	public List<String> match(String str) {

		List<String> list = match(regexPatterns.get(0), str);

		for (int i = 1; i < regexPatterns.size(); i++) {
			Pattern p = regexPatterns.get(i);
			list = match(p, list);
		}
		return list;
	}

	private List<String> match(Pattern p, List<String> strs) {
		List<String> tempList = new ArrayList<String>();
		for (String s : strs) {
			List<String> newList = match(p, s);
			tempList.addAll(newList);
		}
		return tempList;
	}

	private List<String> match(Pattern p, String str) {
		Matcher matcher = p.matcher(str);
		List<String> list = new ArrayList<String>();
		while (matcher.find()) {
			list.add(matcher.group());
		}
		return list;
	}

}
